<script setup lang="tsx">
defineOptions({
  name: "provision"
});

import { ref, computed, nextTick, onMounted, onUnmounted, provide, inject, getCurrentInstance } from "vue";
import { useRouter } from "vue-router";
import { useRouterStoreHook } from "@/store/modules/router";
import search from "@/views/common/fab/provision/components/search.vue";
import modelBox from "@/views/common/components/modelBox/index.vue";
import echartsChart from "@/views/common/components/echartsChart/index.vue";
import commonTable from "@/views/common/components/commonTable/index.vue";
import workbech from "./components/workbech.vue";
import { useLabelLayoutBarChartFn } from "@/hooks/useEcharts";
import { useUpdateDomHeight, useCancelUpdateDomHeight } from "@/hooks/useCommon";
import { queryFabSupplyConsumeOneChamber, queryFabSupplyConsumeChamberRunRecord } from "@/api/modules/fab";
import dayjs from "dayjs";

const { proxy }: any = getCurrentInstance();
const router = useRouter();
const routerStore = useRouterStoreHook();
const routerQuery = inject("routerQuery", ref<Record<string, any>>({}));

const gap = 20;
const defaultHeight = 362;
const provisionTableRef = ref<HTMLElement | null>(null);
const searchRef = ref<InstanceType<typeof search> | null>(null);
const workbechRef = ref<InstanceType<typeof workbech> | null>(null);
const echartsChartRef = ref<InstanceType<typeof echartsChart> | null>(null);
const options = ref<any>(null);
// const dataTypes = ref<Array<string>>(["实际值", "供给值", "设定值"]);
// 产品确认 默认去掉 设定值 供给值
const dataTypes = ref<Array<string>>(["实际值"]);
const commonTableRef = ref<CommonTable.TableRefType>(null);
const searchParams = ref<Record<string, any>>({});
const scrollbarHeight = ref<number>(defaultHeight);
const tableParams = ref<any>({});
const workbechParams = ref<Record<string, any> | null>(null);
const defaultparameter_ = ref<Record<string, any>>({});
const workbechStyle = ref<Record<string, any>>(null);
const workbechKey = ref<string>(Math.random().toString(36).slice(2, 10));
const isAxiosRequire = computed(() => !!tableParams.value.parameter);

provide("defaultparameter", defaultparameter_);
const paginationProps = {
  layout: "total, prev, pager, next",
  pagerCount: "5"
};

interface Props {
  defaultparameter?: Record<string, any>;
}

const props = withDefaults(defineProps<Props>(), { defaultparameter: () => ({ parameter: "" }) });

const tableData = ref<Array<any>>([]);

const _period = ref<string>("week");
const _startTime = ref<string>("");
const _endTime = ref<string>("");
const _parameter = ref<string>("");

const list = ref([]);
const tableCloumns = computed(() => {
  const { name = "" } = defaultparameter_.value;
  return [
    {
      label: "Wafer code",
      prop: "waferId",
      width: 90,
      render({ row, $index }: any) {
        // const { waferId = "" } = row;
        list.value[$index] = row;
        const defaultStyle = () => {
          return {
            width: "100%",
            color: "var(--px-color-primary)",
            cursor: "pointer",
            overflow: "hidden",
            textOverflow: "ellipsis",
            whiteSpace: "nowrap"
          };
        };
        const clickHandler = (row: any) => {
          const className = routerStore.getSubject.toLowerCase();
          const path = `/${className}/fab/provision/craft`;
          const p = searchRef.value?.getParams();
          const { technology = "", product = "", lot = "", waferId = "", wafer = "" } = list.value[$index];
          const query = { ...p, period: _period.value, technology, product, lot, waferId, wafer };
          let params = encodeURI(JSON.stringify(query));
          const { href } = router.resolve({ path, query: { params } });
          window.open(href, "_blank");
        };
        return () => (
          <div style={defaultStyle()} onClick={() => clickHandler(row)}>
            {list.value[$index].waferId}
          </div>
        );
      }
    },
    { label: "开始时间", prop: "startTime", width: 80 },
    { label: "结束时间", prop: "outTime", width: 80 },
    {
      label: `${name}消耗`,
      prop: "value",
      width: 110
    }
  ];
});

const echartsTitle = computed(() => {
  const { eqpId = "" } = routerQuery.value;
  const { name = "" } = defaultparameter_.value;
  return `${eqpId} ${name}耗量统计`;
});

const tableTitle = computed(() => {
  const { eqpId = "" } = routerQuery.value;
  return `${eqpId}跑片历史记录`;
});

const getParams = (flag?: boolean) => {
  const { eqpId = "" } = routerQuery.value;
  const className = routerStore.getSubject !== "ALL" ? routerStore.getSubject : "";
  const p = searchRef.value?.getParams();
  const params = { ...p, className, eqpId };
  return params;
};

/**
 * @description:  search change 事件
 * @param {*} params  搜索条件参数
 * @param {*} types   数据选择
 * @param {*} flag    是否首次触发
 * @param {*} flag2   是否物料数据改变
 * @param {*} flag3   是否从全不选到选择
 * @return {*}
 */
const searchChangeHandler = async (
  params: Record<string, any>,
  types: Array<string>,
  flag: boolean = false,
  flag2: boolean = false,
  flag3: boolean = false
) => {
  workbechKey.value = Math.random().toString(36).slice(2, 10);
  await nextTick();
  searchParams.value = getParams();
  // 1、获取单个chamber数据
  workbechParams.value = { ...searchParams.value };
  workbechRef.value.init(types);
  // 2、获取跑片记录（数据选择改变时不需要更新跑跑片数据）
  if (!flag2) {
    tableParams.value = { ...searchParams.value };
    // 调试
    // tableParams.value = { ...searchParams.value, eqpId: "YTNJT01_CHX" };
  }
  // 3、获取整个机台的数据
  if (types?.length) {
    await initOneChamber();
  } else {
    await initOneChamber(true);
  }
  await nextTick();
  if (flag3) {
    echartsChartRef.value.forceUpdateEcharts();
  } else {
    echartsChartRef.value.updateEchartsOption();
  }
};

const selectChangeHandler = (val: any) => {
  defaultparameter_.value = val;
  searchParams.value.parameter = val.code;
};

const getOptions = (item, flag: boolean = false) => {
  const { singleDTOList = [], headerInformation = "", unit = "" } = item;
  const ec = {};
  // const unit = "";
  const xAxisData = singleDTOList.map(item => dayjs(item.dayStr).format("MM/DD"));
  const consumeData = singleDTOList.map(item => item.consumeValue);
  const supplyData = singleDTOList.map(item => item.supplyValue);
  const setData = singleDTOList.map(item => item.setValue);
  const label = {
    show: true,
    position: "top",
    formatter(params) {
      const { dataIndex = 0 } = params;
      if (typeof dataIndex !== "number") return "";
      const { setValue = 0 } = singleDTOList[dataIndex];
      if (typeof setValue !== "number") return "";
      return setValue;
    }
  };
  const legend = {
    show: true,
    right: 0
  };
  const grid = {
    top: 50,
    bottom: 0,
    left: 4,
    right: 40,
    containLabel: true
  };
  const tooltip: any = {
    trigger: "axis",
    axisPointer: {
      type: "shadow"
    }
  };
  const xAxis = [
    {
      type: "category",
      data: xAxisData
      // axisLabel: {
      //   interval: 0
      // }
    }
  ];
  const yAxis = {
    max(value) {
      return Math.ceil(value.max / 200) * 200;
    }
  };
  let series: Array<any> = [
    {
      name: "设定值",
      type: "line",
      symbol: "none",
      emphasis: { focus: "series" },
      data: setData,
      itemStyle: {
        color: "#FF4545"
      },
      lineStyle: {
        type: "dashed"
      },
      endLabel: {
        show: true,
        formatter: `${setData[0]}`
      }
    },
    {
      name: "实际值",
      type: "bar",
      // stack: "Ad",
      emphasis: { focus: "series" },
      data: flag ? [] : consumeData,
      barGap: "0",
      itemStyle: {
        color: "#3B82F6"
      }
    },
    {
      name: "供给值",
      type: "bar",
      // stack: "Ad",
      emphasis: { focus: "series" },
      data: flag ? [] : supplyData,
      barGap: "0",
      itemStyle: {
        color: "#FFCA45"
      }
    }
  ];
  series = dataTypes.value?.length ? series.filter(item => dataTypes.value.includes(item.name)) : series;
  const ag = { legend, grid, tooltip, xAxis, series };
  return useLabelLayoutBarChartFn(ec, xAxisData, consumeData, headerInformation, unit, null, false, "top", ag);
};

const initOneChamber = async (flag: boolean = false) => {
  echartsChartRef.value.initLoading();
  const params = { ...searchParams.value };
  if (!searchParams.value?.parameter) {
    options.value = null;
    echartsChartRef.value.loadingInstance.close();
    return;
  }
  const res = await queryFabSupplyConsumeOneChamber({ ...params }, err => {
    echartsChartRef.value.loadingInstance.close();
  });
  const flag_ = !options.value;
  options.value = getOptions(res, flag);
  flag_ && echartsChartRef.value?.forceUpdateEcharts();
  echartsChartRef.value.loadingInstance.close();
};

const initStyle = () => {
  const bgImg = proxy.useGetStaticUrl("/ifp-web-static/image/fab/provision/area/workbech.png");
  const backgroundImage = `url(${bgImg})`;
  workbechStyle.value = { backgroundImage };
};

const init = async () => {
  const { eqpId = "", period = "week", startTime = "", endTime = "", parameter = "" } = routerQuery.value;
  if (!eqpId) return null;
  period && (_period.value = period as string);
  startTime && (_startTime.value = startTime as string);
  endTime && (_endTime.value = endTime as string);
  parameter && (_parameter.value = parameter as string);
  initStyle();
};

init();

onMounted(async () => {
  await nextTick();
  await useUpdateDomHeight(scrollbarHeight, provisionTableRef, gap, defaultHeight);
});

onUnmounted(() => useCancelUpdateDomHeight());
</script>

<template>
  <div class="detail-provision">
    <div class="detail-provision-search">
      <search
        ref="searchRef"
        v-model:dataTypes="dataTypes"
        :period="_period"
        :startTime="_startTime"
        :endTime="_endTime"
        :parameter="_parameter"
        @change="searchChangeHandler"
        @selectChange="selectChangeHandler"
      />
    </div>
    <div class="detail-provision-content" :style="{ ...workbechStyle }">
      <workbech ref="workbechRef" :key="workbechKey" :params="workbechParams" />
    </div>
    <div class="detail-provision-data">
      <div class="detail-provision-data-item detail-provision-data-echarts">
        <echartsChart ref="echartsChartRef" :title="echartsTitle" :options="options" />
      </div>
      <div class="detail-provision-data-item detail-provision-data-table">
        <modelBox :title="tableTitle">
          <div ref="provisionTableRef">
            <commonTable
              v-if="!!tableData?.length"
              ref="commonTableRef"
              v-model="tableData"
              mode="stripe"
              :border="false"
              :tableCloumns="tableCloumns"
              :height="scrollbarHeight"
              :paginationProps="paginationProps"
              :axiosApi="queryFabSupplyConsumeChamberRunRecord"
              :params="tableParams"
              :isAxiosRequire="isAxiosRequire"
            />
            <div v-else class="detail-provision-empty">
              <px-empty class="px-empty-common" />
            </div>
          </div>
        </modelBox>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.detail-provision {
  display: flex;
  gap: 16px;
  align-items: flex-start;
  width: 100%;
  height: calc(100vh - 90px);

  .detail-provision-search {
    box-sizing: border-box;
    padding: 16px;
    background-color: #fff;
    border-radius: 4px;
  }

  .detail-provision-content {
    position: relative;
    flex: 1;
    min-width: 600px;
    height: 100%;
    min-height: 600px;
    background-repeat: no-repeat;
    background-attachment: scroll;
    background-position: center center;
    background-position: 70% 55%;
    background-size: 70% 70%;
  }

  .detail-provision-data {
    display: flex;
    flex-direction: column;
    gap: 16px;
    width: 450px;
    height: 100%;

    .detail-provision-data-item {
      box-sizing: border-box;
      width: 100%;
      background-color: #fff;
      border-radius: 4px;
    }

    .detail-provision-data-echarts {
      flex: 2;
    }

    .detail-provision-data-table {
      flex: 3;
      .detail-provision-empty {
        width: 100%;
        height: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}
</style>
